package com.ruoyi.common.utils;

import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.text.Convert;

import java.util.HashMap;
import java.util.Map;

public class LocalUserUtils {
    private static ThreadLocal<Map<String,String>> localUser = new ThreadLocal<>();

    private static Map<String,String> getUserMap() {
        Map<String, String> userMap = localUser.get();
        if (localUser.get() == null) {
            userMap = new HashMap<>();
            localUser.set(userMap);
        }
        return userMap;
    }

    /**
     * 获取用户账号
     */
    public static String getUsername() {
        String username = getUserMap().get(CacheConstants.DETAILS_USERNAME);
        return ServletUtils.urlDecode(username == null ? "" : username);
    }

    public static void setUserName(String userName) {
        getUserMap().put(CacheConstants.DETAILS_USERNAME, userName);
    }

    /**
     * 获取用户名称
     */
    public static String getRealName() {
        String realName = getUserMap().get(CacheConstants.DETAILS_REALNAME);
        return ServletUtils.urlDecode(realName == null ? "":realName);
    }

    public static void setRealName(String realName) {
        getUserMap().put(CacheConstants.DETAILS_REALNAME, realName);
    }

    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        return Convert.toLong(getUserMap().get(CacheConstants.DETAILS_USER_ID));
    }

    public static void setUserId(String userId) {
        getUserMap().put(CacheConstants.DETAILS_USER_ID, userId);
    }

    /**
     * 获取部门id
     */
    public static Long getDeptId() {
        return Convert.toLong(getUserMap().get(CacheConstants.DETAILS_DEPT_ID));
    }

    public static void setDeptId(String deptId) {
        getUserMap().put(CacheConstants.DETAILS_DEPT_ID, deptId);
    }

    /**
     * 获取部门名称
     */
    public static String getDeptName() {
        String deptName = getUserMap().get(CacheConstants.DETAILS_DEPT_NAME);
        return ServletUtils.urlDecode(deptName == null ? "":deptName);
    }

    public static void setDeptName(String deptName) {
        getUserMap().put(CacheConstants.DETAILS_DEPT_NAME, deptName);
    }

    /**
     * 获取公司id
     */
    public static Long getCompanyId() {
        return Convert.toLong(getUserMap().get(CacheConstants.DETAILS_COMPANY_ID));
    }

    public static void setCompanyId(String companyId) {
        getUserMap().put(CacheConstants.DETAILS_COMPANY_ID, companyId);
    }

    /**
     * 获取公司名称
     */
    public static String getCompanyName() {
        String companyName = getUserMap().get(CacheConstants.DETAILS_COMPANY_NAME);
        return ServletUtils.urlDecode(companyName == null ? "":companyName);
    }

    public static void setCompanyName(String companyName) {
        getUserMap().put(CacheConstants.DETAILS_COMPANY_NAME, companyName);
    }

    /**
     * 清理当前用户
     */
    public static void clearLocalUser() {
        LocalUserUtils.localUser.remove();
    }

}
